/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import com.hiddenequity.campaign_targeting_service.CampaignTargetingResponseParser;
import com.hiddenequity.campaign_targeting_service.CampaignTargetingService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.City;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.Country;
import com.hiddenequity.utils.LocationDataProvider;
import com.hiddenequity.utils.Province;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;

public class Act_CampaignGeoTarget extends Act_Super{
	
	String campaignId;
	
	String campaignName;
	
	private static ArrayList<Country> countryArray = new ArrayList<Country>();
	
	private static ArrayList<City> worldCityArray = new ArrayList<City>();
	
	private static ArrayList<Province> provinceArray = new ArrayList<Province>();
	
	private final int COUNTRY_CITY_INTERSECTION = 0;
	private final int COUNTRY_PROVINCE_INTERSECTION = 1;
	private final int PROVINCE_CITY_INTERSECTION = 2;
	
	private final int UNION_COUNTRY_LEVEL = 0;
	private final int UNION_PROVINCE_LEVEL = 1;
	
	private CityAdapter _cityAdapter = new CityAdapter();
	private ProvinceAdapter _provinceAdapter = new ProvinceAdapter();
	private CountryAdapter _countryAdapter = new CountryAdapter();

    private static ArrayList<Country> rawSelectedCountry = new ArrayList<Country>();
    private static ArrayList<Country> selectedCountry = new ArrayList<Country>();

    private static ArrayList<Province> rawSelectedProvince = new ArrayList<Province>(); 
    private static ArrayList<Province> selectedProvince = new ArrayList<Province>();
    
    private static ArrayList<City> rawSelectedCity = new ArrayList<City>(); 
    private static ArrayList<City> selectedCity = new ArrayList<City>();

    
    
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	
	private MultiAutoCompleteTextView mcCountryCode;
	private MultiAutoCompleteTextView mcProvince;
	private MultiAutoCompleteTextView mcCities;
	private LinearLayout progressBar;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.super_operation_layout);
		
		((ViewStub) findViewById(R.id.stub_campaign_geo_target)).inflate();
        
		Intent intent = getIntent();
        campaignId = intent.getStringExtra("campaignId");
        campaignName = intent.getStringExtra("campaignName");
        
        title.setText(R.string.title_geo_set);
        sub_title.setText(campaignName);
        filter.setVisibility(View.GONE);
        
        runOperationasync(OPERATION_PREPARE_DATA, getString(R.string.progress_preparing), false);

    }//onCreate

    
    
    private void initializeForm(){
       
    	progressBar = (LinearLayout) findViewById(R.id.progress_button_bar);
    	
    	//Country matv
        mcCountryCode = (MultiAutoCompleteTextView) findViewById(R.id.mcCountryCode);
        mcCountryCode.setThreshold(3);
        mcCountryCode.setAdapter(_countryAdapter);
        mcCountryCode.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
        
        mcCountryCode.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				rawSelectedCountry.add((Country) arg0.getItemAtPosition(arg2));
				actualizeCountryData(false);
				performGeoUnion(UNION_COUNTRY_LEVEL);
			}
		});


        //Province matv
        mcProvince  = (MultiAutoCompleteTextView) findViewById(R.id.mcProvince);
        mcProvince.setThreshold(3);
        mcProvince.setAdapter(_provinceAdapter);
        mcProvince.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

        mcProvince.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				rawSelectedProvince.add((Province) arg0.getItemAtPosition(arg2));
				actualizeProvinceData(false);
				performGeoUnion(UNION_PROVINCE_LEVEL);
			}
		});
        
        
        //City matv
        mcCities = (MultiAutoCompleteTextView) findViewById(R.id.mcCities);
        mcCities.setThreshold(3);
        mcCities.setAdapter(_cityAdapter);
        mcCities.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
        
        mcCities.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				rawSelectedCity.add((City) arg0.getItemAtPosition(arg2));
				actualizeCityData(false);
			}
		});    	
    }
    
    
    
    /*
     * Custom base adapter for city auto complete
     */
    private class CityAdapter extends BaseAdapter implements Filterable
    {
    	private List<City> filteredCities = new ArrayList<City>();
    	
		public int getCount() {
			return filteredCities.size();
		}

		public Object getItem(int position) {
			return filteredCities.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			LayoutInflater mInflater;
			if (row == null) {
				mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				row = mInflater.inflate(R.layout.list_autocomplete, null);
			}

			City city = (City) getItem(position);
			
    		if (city != null) {
    			TextView tv = (TextView) row.findViewById(R.id.autocomplete);
    			if (tv != null)
    				tv.setText(city.toString());
    		}	
    		return row;
		}

		public Filter getFilter() {
			return _filter;
		}
		
		private final Filter _filter = new Filter() {
			
			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint, FilterResults results) {
				filteredCities.clear();
				if(results != null && results.values != null && results.values instanceof List<?>)
					filteredCities.addAll((List<City>)results.values);
				CityAdapter.this.notifyDataSetChanged();
			}
			
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				if(constraint == null)
					return null;
				
				Act_CampaignGeoTarget.this.runOnUiThread(new Runnable() {
					 public void run() {
						 Act_CampaignGeoTarget.this.actualizeCountryData(false);
						 Act_CampaignGeoTarget.this.actualizeProvinceData(false);
						 Act_CampaignGeoTarget.this.actualizeCityData(true);
						 progressBar.setVisibility(View.VISIBLE);
					 }
				});

        		List<City> validCities = new ArrayList<City>(); 
        		for(City city : Act_CampaignGeoTarget.worldCityArray) {
        			if(isGeoIntersection(COUNTRY_CITY_INTERSECTION, city) || isGeoIntersection(PROVINCE_CITY_INTERSECTION, city))
        				continue;
        			if(city.toString().toLowerCase().startsWith(constraint.toString().toLowerCase()) && !isCitySelected(city) ){
        				validCities.add(city);
        			}
	
        		}

				Act_CampaignGeoTarget.this.runOnUiThread(new Runnable() {
					 public void run() {
						 progressBar.setVisibility(View.GONE);
					 }
				});
        		
        		FilterResults results = new FilterResults();
				
				results.count = validCities.size();
				results.values = validCities;
				
				return results;
			}
		}; 
    	
    }//CityAdapter

   
    
    /*
     * Check if city allready selected
     */
    private boolean isCitySelected(City city){
    	boolean result = false;
    	
    	for(City c : selectedCity){
    		if(c.getCityName().equals(city.getCityName()))
    			result = true;
    	}
    	
    	return result;
    }
    
    
    
    /*
     * Custom base adapter for province auto complete
     */
    private class ProvinceAdapter extends BaseAdapter implements Filterable
    {
    	private List<Province> filteredCities = new ArrayList<Province>();
    	
		public int getCount() {
			return filteredCities.size();
		}

		public Object getItem(int position) {
			return filteredCities.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			LayoutInflater mInflater;
			if (row == null) {
				mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				row = mInflater.inflate(R.layout.list_autocomplete, null);
			}

			Province province = (Province) getItem(position);
			
    		if (province != null) {
    			TextView tv = (TextView) row.findViewById(R.id.autocomplete);
    			if (tv != null)
    				tv.setText(province.toString());
    		}	
    		return row;
		}

		public Filter getFilter() {
			return _filter;
		}
		
		private final Filter _filter = new Filter() {
			
			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint, FilterResults results) {
				filteredCities.clear();
				if(results != null && results.values != null && results.values instanceof List<?>)
					filteredCities.addAll((List<Province>)results.values);
				ProvinceAdapter.this.notifyDataSetChanged();
			}
			
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				if(constraint == null)
					return null;
				
				Act_CampaignGeoTarget.this.runOnUiThread(new Runnable() {
					 public void run() {
						 Act_CampaignGeoTarget.this.actualizeCountryData(false);
						 Act_CampaignGeoTarget.this.actualizeProvinceData(true);
					 }
				});

        		List<Province> validProvinces = new ArrayList<Province>(); 
        		for(Province province : Act_CampaignGeoTarget.provinceArray) {
        			if(isGeoIntersection(COUNTRY_PROVINCE_INTERSECTION, province))
        				continue;
        			
        			if(province.toString().toLowerCase().startsWith(constraint.toString().toLowerCase()) && !selectedProvince.contains(province)){
        				validProvinces.add(province);
        			}
	
        		}
        			
        		FilterResults results = new FilterResults();
				
				results.count = validProvinces.size();
				results.values = validProvinces;
				
				return results;
			}
		}; 
    	
    }//ProvinceAdapter
 
    
    
    /*
     * Custom base adapter for country auto complete
     */
    private class CountryAdapter extends BaseAdapter implements Filterable
    {
    	private List<Country> filteredCountry = new ArrayList<Country>();
    	
		public int getCount() {
			return filteredCountry.size();
		}

		public Object getItem(int position) {
			return filteredCountry.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			LayoutInflater mInflater;
			if (row == null) {
				mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				row = mInflater.inflate(R.layout.list_autocomplete, null);
			}

			Country country = (Country) getItem(position);
			
    		if (country != null) {
    			TextView tv = (TextView) row.findViewById(R.id.autocomplete);
    			if (tv != null)
    				tv.setText(country.toString());
    		}	
    		return row;
		}

		public Filter getFilter() {
			return _filter;
		}
		
		private final Filter _filter = new Filter() {
			
			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint, FilterResults results) {
				filteredCountry.clear();
				if(results != null && results.values != null && results.values instanceof List<?>)
					filteredCountry.addAll((List<Country>)results.values);
				CountryAdapter.this.notifyDataSetChanged();
			}
			
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				if(constraint == null)
					return null;
				
				Act_CampaignGeoTarget.this.runOnUiThread(new Runnable() {
					 public void run() {
						 Act_CampaignGeoTarget.this.actualizeCountryData(true);
						 Act_CampaignGeoTarget.this.actualizeProvinceData(false);
						 Act_CampaignGeoTarget.this.actualizeCityData(false);
					 }
				});

        		List<Country> validProvinces = new ArrayList<Country>(); 
        		
        		for(Country country : Act_CampaignGeoTarget.countryArray) {
        			if(country.toString().toLowerCase().startsWith(constraint.toString().toLowerCase()) && !selectedCountry.contains(country)){
        				validProvinces.add(country);
        			}	
        		}
        			
        		FilterResults results = new FilterResults();
				
				results.count = validProvinces.size();
				results.values = validProvinces;
				
				return results;
			}
		}; 
    	
    }//CountryAdapter
    
    
    
    /*
     * Perform geo union
     */
    private void performGeoUnion(int unionLevel){
    	switch (unionLevel) {
			case UNION_COUNTRY_LEVEL:
		        
				if(!selectedCountry.isEmpty()){
		            
					selectedProvince.clear();
		            for(Province p : rawSelectedProvince){
		            	if(!isGeoIntersection(COUNTRY_PROVINCE_INTERSECTION, p))
		            		selectedProvince.add(p);		            	
		            }        	

			        rawSelectedProvince.clear();
			        rawSelectedProvince.addAll(selectedProvince);
				
			        
		        	mcProvince.clearComposingText();
		            
		            String actualSelection = "";
		            
		            for(Province c : selectedProvince){
		            	actualSelection = actualSelection + c.toString() + ", ";
		            }
		            
		            mcProvince.setText(actualSelection);
		            mcProvince.setSelection(actualSelection.length());
	            
			        selectedCity.clear();
			        for(City c : rawSelectedCity){
			        	if(!isGeoIntersection(COUNTRY_CITY_INTERSECTION, c))
			        		selectedCity.add(c);
			        }
			        
			        rawSelectedCity.clear();
			        rawSelectedCity.addAll(selectedCity);
			        
		        	mcCities.clearComposingText();
		            
		            actualSelection = "";
		            
		            for(City c : selectedCity){
		            	actualSelection = actualSelection + c.toString() + ", ";
		            }
		            
		            mcCities.setText(actualSelection);   
		            mcCities.setSelection(actualSelection.length());

				}

				break;
				
			case UNION_PROVINCE_LEVEL:
				
				if(!selectedProvince.isEmpty()){
			        selectedCity.clear();
			        for(City c : rawSelectedCity){
			        	if(!isGeoIntersection(PROVINCE_CITY_INTERSECTION, c))
			        		selectedCity.add(c);
			        }
			        
			        rawSelectedCity.clear();
			        rawSelectedCity.addAll(selectedCity);
			        
		        	mcCities.clearComposingText();
		            
		            String actualSelection = "";
		            
		            for(City c : selectedCity){
		            	actualSelection = actualSelection + c.toString() + ", ";
		            }
		            
		            mcCities.setText(actualSelection);   
		            mcCities.setSelection(actualSelection.length());
			        
				}
				
				break;
		}
    	
    }
    
    
    /*
     * Check geo intersection
     */
    private boolean isGeoIntersection(int intersectionType, Object oIntersect){
		boolean result = false;
    	
		City city;
		String countryCode;
		String provinceCode;
		switch (intersectionType) {
			case COUNTRY_CITY_INTERSECTION:
				
				city = (City) oIntersect;
				
	            for(Country country : selectedCountry){
	            	countryCode = country.getCode();
	            	if(countryCode.equals(city.getCountryCode()))
	            		result = true;
	            }				
	            
				break;
				
			case COUNTRY_PROVINCE_INTERSECTION:
				
				Province province = (Province) oIntersect;
				
	            for(Country country : selectedCountry){
	            	countryCode = country.getCode();
	            	if(countryCode.equals(province.getCountryCode()))
	            		result = true;
	            }					
				
				break;
				
			case PROVINCE_CITY_INTERSECTION:
				city = (City) oIntersect;
	            for(Province p : selectedProvince){
	            	provinceCode = p.getProvinceCode();
	            	if(provinceCode.equals(city.getProvinceCode()))
	            		result = true;
	            }					
				break;
		
		}
		return result;
    }//isGeoIntersection
   
     
    
    /*
     * Selected country actualization
     */
    private void actualizeCountryData(boolean isSelfActualizer){
    	selectedCountry.clear();
    	
    	//MultiAutoCompleteTextView mt = (MultiAutoCompleteTextView) findViewById(R.id.mcCountryCode);
    	
    	String text = mcCountryCode.getText().toString();

        StringTokenizer stArr = new StringTokenizer(text, ",");

        while(stArr.hasMoreTokens()){
        	String cName = stArr.nextToken().trim();
            for(Country c : rawSelectedCountry){
            	String sName = c.getName();
            	if(sName.equals(cName)){
            		selectedCountry.add(c);
            	}
            }
        }
        
        rawSelectedCountry.clear();
        rawSelectedCountry.addAll(selectedCountry);
        
        if(!isSelfActualizer){
        	mcCountryCode.clearComposingText();
            
            String actualSelection = "";
            
            for(Country c : selectedCountry){
            	actualSelection = actualSelection + c.toString() + ", ";
            }
            
            mcCountryCode.setText(actualSelection);
            mcCountryCode.setSelection(actualSelection.length());
        }
      
    }//actualizeCountryData
   
    
    
    /*
     * Selected Province actualization
     */
    private void actualizeProvinceData(boolean isSelfActualizer){
    	selectedProvince.clear();

    	String text = mcProvince.getText().toString();

        StringTokenizer stArr = new StringTokenizer(text, ",");

        while(stArr.hasMoreTokens()){
        	String cName = stArr.nextToken().trim();
            for(Province p : rawSelectedProvince){
            	String sName = p.toString();
            	if(sName.equals(cName) ){
            		selectedProvince.add(p);
            	}
            }
        }
        
        rawSelectedProvince.clear();
        rawSelectedProvince.addAll(selectedProvince);
        
        if(!isSelfActualizer){
        	mcProvince.clearComposingText();
            
            String actualSelection = "";
            
            for(Province c : selectedProvince){
            	actualSelection = actualSelection + c.toString() + ", ";
            }
            
            mcProvince.setText(actualSelection);
            mcProvince.setSelection(actualSelection.length());
        }
    }//actualizeProvinceData
    

    
    /*
     * Selected city actualization
     */
    private void actualizeCityData(boolean isSelfActualizer){
    	selectedCity.clear();
    	
    	//MultiAutoCompleteTextView mt = (MultiAutoCompleteTextView) findViewById(R.id.mcCities);
    	
    	String text = mcCities.getText().toString();

        StringTokenizer stArr = new StringTokenizer(text, ",");

        while(stArr.hasMoreTokens()){
        	String cName = stArr.nextToken().trim();
            for(City c : rawSelectedCity){
            	String sName = c.toString();
            	if(sName.equals(cName)){
            		selectedCity.add(c);
            	}
            }
        }
        
        rawSelectedCity.clear();
        rawSelectedCity.addAll(selectedCity);
        
        if(!isSelfActualizer){
        	mcCities.clearComposingText();
            
            String actualSelection = "";
            
            for(City c : selectedCity){
            	actualSelection = actualSelection + c.toString() + ", ";
            }
            
            mcCities.setText(actualSelection);   
            mcCities.setSelection(actualSelection.length());
        }
    }//actualizeCityData   
   
    
	/*
	 * Asinc data request
	 */
    
	private void runOperationasync(final int operation, String message, boolean overlap) {
		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_CampaignGeoTarget.this, getApplication());

				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_PREPARE_DATA:
							if (Act_CampaignGeoTarget.provinceArray.isEmpty())
								Act_CampaignGeoTarget.provinceArray = LocationDataProvider
										.getProvinceList(getApplication());
							if (Act_CampaignGeoTarget.countryArray.isEmpty())
								Act_CampaignGeoTarget.countryArray = LocationDataProvider
										.getCountryList(getApplication());
							if (Act_CampaignGeoTarget.worldCityArray.isEmpty())
								Act_CampaignGeoTarget.worldCityArray = LocationDataProvider
										.getCityList(getApplication());
							break;
						case OPERATION_GET_DATA:
							if (campaignId != null)
								Act_CampaignGeoTarget.this
										.getCampaignGeoTarget();
							break;
						case OPERATION_SET_DATA:
							Act_CampaignGeoTarget.this.setCampaignGeoTarget();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// Perform postoperation
				Act_CampaignGeoTarget.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {
							case OPERATION_PREPARE_DATA:
								initializeForm();
								if (campaignId != null)
									runOperationasync(
											OPERATION_GET_DATA,
											getString(R.string.progress_loading),
											true);
								break;
							case OPERATION_GET_DATA:
								setUpForm();
								break;
							case OPERATION_SET_DATA:
								if (responseErrorString == null)
									Act_CampaignGeoTarget.this.finish();
								break;
							}

						} else {
							Intent intent = new Intent(
									Act_CampaignGeoTarget.this
											.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();

	}//runOperationasync
    

	
	/*
	 * Get geo target info
	 */
	private void getCampaignGeoTarget(){
    	
		CampaignTargetingResponseParser targetingParser = new CampaignTargetingResponseParser(
    			Communication.postSOAP(
    					CampaignTargetingService.URL_CAMPAIGN_TARGET_SERVICE, 
    					CampaignTargetingService.getCampaignTargetById(campaignId)
    				)
    			);
    	
		responseErrorString = targetingParser.checkForErrors();
    	
    	selectedCity.clear();
    	selectedCity.addAll(targetingParser.getCampaignGeoCityTarget());
    	
    	selectedProvince.clear();
    	selectedProvince.addAll(targetingParser.getCampaignGeoProvinceTarget());
    	
    	selectedCountry.clear();
    	selectedCountry.addAll(targetingParser.getCampaignGeoCountryTarget());
	}
    
	
	
	/*
	 * Set up form
	 */
	private void setUpForm(){
		//Country data
		
		rawSelectedCountry.clear();
		
		for(Country country : countryArray){
			for(Country sCountry : selectedCountry){
				if(country.getCode().equals(sCountry.getCode())){
					rawSelectedCountry.add(country);
				}
			}
		}

		selectedCountry.clear();
		selectedCountry.addAll(rawSelectedCountry);
		
    	mcCountryCode.clearComposingText();
        
        String actualSelection = "";
        
        for(Country c : selectedCountry){
        	actualSelection = actualSelection + c.toString() + ", ";
        }
        
        mcCountryCode.setText(actualSelection);
        mcCountryCode.setSelection(actualSelection.length());
		
		
        //Province data
        
        rawSelectedProvince.clear();
        
		for(Province province : provinceArray){
			for(Province sProvince : selectedProvince){
				if(province.getProvinceCode().equals(sProvince.getProvinceCode())){
					rawSelectedProvince.add(province);
				}
			}
		}
		
		selectedProvince.clear();
		selectedProvince.addAll(rawSelectedProvince);

    	mcProvince.clearComposingText();
        
        actualSelection = "";
        
        for(Province p : selectedProvince){
        	actualSelection = actualSelection + p.toString() + ", ";
        }
        
        mcProvince.setText(actualSelection);
        mcProvince.setSelection(actualSelection.length());       
        
        
        //City data
        
        rawSelectedCity.clear();
        
		for(Province province : provinceArray){
			for(City city : selectedCity){
				if(province.getProvinceCode().equals(city.getProvinceCode())){
					city.setProvinceName(province.getProvinceName());
					city.setCountryCode(province.getCountryCode());
					city.setCountryName(province.getCountryName());
					//rawSelectedCity.add(object)
				}
			}
		}
		
		rawSelectedCity.clear();
		rawSelectedCity.addAll(selectedCity);

    	mcCities.clearComposingText();
        
        actualSelection = "";
        
        for(City c : selectedCity){
        	actualSelection = actualSelection + c.toString() + ", ";
        }
        
        mcCities.setText(actualSelection);
        mcCities.setSelection(actualSelection.length());      
	}
	
	
	
	/*
	 * Set campaign geo target
	 */
	private void setCampaignGeoTarget(){
		CampaignTargetingResponseParser targetingParser = new CampaignTargetingResponseParser(
    			Communication.postSOAP(
    					CampaignTargetingService.URL_CAMPAIGN_TARGET_SERVICE, 
    					CampaignTargetingService.setGeoTarget(campaignId, selectedCountry, selectedProvince, selectedCity)
    				)
    			);
    	
		responseErrorString = targetingParser.checkForErrors();		
	}//setCampaignGeoTarget
    
	
	
    /*
     * Button save handler
     */
    public void onClick_saveData(View v){
    	actualizeCityData(false);
    	actualizeCountryData(false);
    	actualizeProvinceData(false);
    	runOperationasync(OPERATION_SET_DATA, getString(R.string.progress_saving), false);
    }

}
